package mamikeji.liaowa.ui.activity.clock;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.bigkoo.pickerview.TimePickerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.ClockListTimetAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MD5Util;
import mamikeji.liaowa.utils.MaxTextLength;
import mamikeji.liaowa.utils.SystemUtils;
import mamikeji.liaowa.widget.clock.AlarmService;
import mamikeji.liaowa.widget.clock.Model.AlarmModel;
import mamikeji.liaowa.widget.clock.data.MyAlarmDataBase;

public class ClockDateActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ClockDateActivity";
    @BindView(R.id.editText_clock_date_title)
    public EditText editText_clock_date_title;
    @BindView(R.id.imageView_clock_date_add)
    public ImageView imageView_clock_date_add;
    @BindView(R.id.imageView_clock_date_opentime)
    public ImageView imageView_clock_date_opentime;
    @BindView(R.id.editText_clock_date_remark)
    public EditText editText_clock_date_remark;
    @BindView(R.id.listView_clock_date)
    public ListView listView_clock_date;
    @BindView(R.id.checkbox_clock_date_week_1)
    public CheckBox checkbox_clock_date_week_1;
    @BindView(R.id.checkBox_clock_date_week_2)
    public CheckBox checkBox_clock_date_week_2;
    @BindView(R.id.checkBox_clock_date_week_3)
    public CheckBox checkBox_clock_date_week_3;
    @BindView(R.id.checkBox_clock_date_week_4)
    public CheckBox checkBox_clock_date_week_4;
    @BindView(R.id.checkBox_clock_date_week_5)
    public CheckBox checkBox_clock_date_week_5;
    @BindView(R.id.checkBox_clock_date_week_6)
    public CheckBox checkBox_clock_date_week_6;
    @BindView(R.id.checkBox_clock_date_week_7)
    public CheckBox checkBox_clock_date_week_7;

    List<String> timeList = new ArrayList<>();
    @BindView(R.id.linearLayout_clock_week)
    LinearLayout linearLayoutClockWeek;
    @BindView(R.id.view_clock_week)
    View viewClockWeek;

    private TimePickerView pvTime;

    private ClockListTimetAdapter clockListTimetAdapter;

    private Boolean aBoolean = false;//星期是否可点击

    private int type_num;

    private int mHour, mMinute;
    private String mTime, mRing;
    private String mRepeatType, mRepeatCode;
    private MyAlarmDataBase db;
    private List<Integer> repeatCode = new ArrayList<>();
    private List<ServiceConnection> serviceConnectionList;

    List<String> weekCode;
    List<String> weekName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_date);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftBtn();
        setTitleName(R.string.clock_date_name);
        setTitleRightBtn(R.string.clock_date_save, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(editText_clock_date_title.getText().toString())) {
                    ForToast.showToast("请输入闹钟名称");
                    return;
                }
                if (timeList == null || timeList.size() <= 0) {
                    ForToast.showToast("请选择闹钟提醒时间");
                    return;
                }
                if (aBoolean) {
                    if (weekCode == null || weekCode.size() == 0) {
                        ForToast.showToast("请选择重复提醒时间");
                        return;
                    }
                }

                addClock(editText_clock_date_title.getText().toString());
            }
        });

        Intent intent = getIntent();
        int type_num = Integer.parseInt(intent.getStringExtra("Clock_Type"));
        String type_name = intent.getStringExtra("Clock_name");

        editText_clock_date_title.setFocusable(type_num == 8 ? true : false);
        editText_clock_date_title.setFocusableInTouchMode(type_num == 8 ? true : false);
        if (type_num != 8) {
            editText_clock_date_title.setText(type_name);
            editText_clock_date_title.setHint("");
            isKeyboardShownToHideKeyboard();
        }else {
            editText_clock_date_title.setHint(type_name);
        }
        init();
    }

    private void init() {
        viewClockWeek.setVisibility(aBoolean ? View.VISIBLE : View.GONE);
        linearLayoutClockWeek.setVisibility(aBoolean ? View.VISIBLE : View.GONE);

        InputFilter[] filters = new InputFilter[]{new MaxTextLength(54)};
        editText_clock_date_remark.setFilters(filters);

        InputFilter[] filters_1 = new InputFilter[]{new MaxTextLength(16)};
        editText_clock_date_title.setFilters(filters_1);

        isKeyboardShownToHideKeyboard();
        clockListTimetAdapter = new ClockListTimetAdapter(timeList, this);
        listView_clock_date.setAdapter(clockListTimetAdapter);

        weekCode = new ArrayList<>();
        weekName = new ArrayList<>();

        checkbox_clock_date_week_1.setOnCheckedChangeListener(new CheckedChangeListener(1));
        checkBox_clock_date_week_2.setOnCheckedChangeListener(new CheckedChangeListener(2));
        checkBox_clock_date_week_3.setOnCheckedChangeListener(new CheckedChangeListener(3));
        checkBox_clock_date_week_4.setOnCheckedChangeListener(new CheckedChangeListener(4));
        checkBox_clock_date_week_5.setOnCheckedChangeListener(new CheckedChangeListener(5));
        checkBox_clock_date_week_6.setOnCheckedChangeListener(new CheckedChangeListener(6));
        checkBox_clock_date_week_7.setOnCheckedChangeListener(new CheckedChangeListener(7));

        time_data();

        clockListTimetAdapter.setOnItemClickListener(new ClockListTimetAdapter.OnItemClickListener() {
            @Override
            public void onDeleteOnClick(int position) {
                timeList.remove(position);
                clockListTimetAdapter.setList(timeList);
            }
        });
    }

    public void time_data() {
        boolean[] booleen = new boolean[]{false, false, false, true, true, false};
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                timeList.add(getTime(date));
                clockListTimetAdapter.setList(timeList);
            }
        })
                .setType(booleen)//默认全部显示
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    @OnClick({
            R.id.imageView_clock_date_add,
            R.id.imageView_clock_date_opentime})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageView_clock_date_add:
                isKeyboardShownToHideKeyboard();
                pvTime.show();
                break;
            case R.id.imageView_clock_date_opentime:
                if (aBoolean) {
                    System.out.println("true");
                    imageView_clock_date_opentime.setImageResource(R.drawable.icon_guanbi_n);
                    checkbox_clock_date_week_1.setEnabled(false);
                    checkBox_clock_date_week_2.setEnabled(false);
                    checkBox_clock_date_week_3.setEnabled(false);
                    checkBox_clock_date_week_4.setEnabled(false);
                    checkBox_clock_date_week_5.setEnabled(false);
                    checkBox_clock_date_week_6.setEnabled(false);
                    checkBox_clock_date_week_7.setEnabled(false);
                    aBoolean = false;
                } else {
                    System.out.println("false");
                    imageView_clock_date_opentime.setImageResource(R.drawable.icon_kaiqi_n);
                    checkbox_clock_date_week_1.setEnabled(true);
                    checkBox_clock_date_week_2.setEnabled(true);
                    checkBox_clock_date_week_3.setEnabled(true);
                    checkBox_clock_date_week_4.setEnabled(true);
                    checkBox_clock_date_week_5.setEnabled(true);
                    checkBox_clock_date_week_6.setEnabled(true);
                    checkBox_clock_date_week_7.setEnabled(true);
                    aBoolean = true;
                }
                viewClockWeek.setVisibility(aBoolean ? View.VISIBLE : View.GONE);
                linearLayoutClockWeek.setVisibility(aBoolean ? View.VISIBLE : View.GONE);
                break;
        }
    }

    public void addClock(String title) {
        showLoading();
        db = new MyAlarmDataBase(ClockDateActivity.this);
        String parentID = null;
        try {
            parentID = MD5Util.md5Encode(String.valueOf(System.currentTimeMillis()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        serviceConnectionList = new ArrayList<>();
        for (int i = 0; i < timeList.size(); i++) {
            System.out.println("添加parent_id:" + parentID);
            mRepeatType = aBoolean ? "" : "只响一次";
            mRepeatCode = "";
            if (aBoolean) {
                if (weekCode != null && weekCode.size() > 0) {
                    for (int a = 0; a < weekCode.size(); a++) {
                        if (a == weekCode.size() - 1) {
                            mRepeatCode = mRepeatCode + weekCode.get(a);
                        } else {
                            mRepeatCode = mRepeatCode + weekCode.get(a) + ",";
                        }
                    }
                }
                if (weekName != null && weekName.size() > 0) {
                    for (int b = 0; b < weekName.size(); b++) {
                        if (b == weekName.size() - 1) {
                            mRepeatType = mRepeatType + weekName.get(b);
                        } else {
                            mRepeatType = mRepeatType + weekName.get(b) + ",";
                        }
                    }
                }
            }

            final String mTime = timeList.get(i);
            //usercode,闹钟名称，闹钟备注，时间，星期，星期代码，停闹方式，mActive，响铃方式，parentID。
            final int id = db.addAlarm(new AlarmModel(
                    ForPreference.getString(ForContents.USER_CODE),
                    title,
                    editText_clock_date_remark.getText().toString(),
                    mTime,
                    mRepeatType,
                    mRepeatCode,
                    "常规",
                    "true",
                    "响铃",
                    parentID
            ));
            ServiceConnection connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    AlarmService.MyBinder binder = (AlarmService.MyBinder) service;
                    switch (mRepeatType) {
                        case "只响一次":
                            binder.setSingleAlarm(getApplicationContext(), mTime, id);
                            break;
                        default:
                            binder.setDiyAlarm(getApplicationContext(), mRepeatType, mTime, id, mRepeatCode);
                            repeatCode.clear();
                            break;
                    }

                    ForLog.d("AddActivity", "绑定服务");
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            Intent intent = new Intent(ClockDateActivity.this, AlarmService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);

            serviceConnectionList.add(connection);
        }
        int num = ForPreference.getInt(ForContents.APP_CLOCK_COUNT) + 1;
        ForPreference.putInt(ForContents.APP_CLOCK_COUNT, num);
        hideLoading();
        finish();
    }

    /**
     * 判断软键盘是否弹起如弹起则隐藏
     */
    private void isKeyboardShownToHideKeyboard() {
        if (SystemUtils.isKeyboardShown(editText_clock_date_title.getRootView())) {
            SystemUtils.hideKeyboard(this, editText_clock_date_title.getApplicationWindowToken());
        }
    }

    public void getTimeDate() {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.CLOCK_ADD_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.CLOCK_ADD_TypeName, editText_clock_date_title.getText().toString());
        formMap.put(HttpKey.CLOCK_ADD_id, "0");
        formMap.put(HttpKey.CLOCK_ADD_TimeGuid, UUID.randomUUID().toString());

        formMap.put(HttpKey.CLOCK_ADD_Time, null);
        formMap.put(HttpKey.CLOCK_ADD_Repeat, (aBoolean ? 1 : 2) + "");
        formMap.put(HttpKey.CLOCK_ADD_Type, type_num + "");

        formMap.put(HttpKey.CLOCK_ADD_Week, null);
        formMap.put(HttpKey.CLOCK_ADD_Remark, editText_clock_date_remark.getText().toString());
        formMap.put(HttpKey.CLOCK_ADD_OpenTime, "1");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SAVE_ALARMCLOCK, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        startActivity(new Intent(ClockDateActivity.this, ClockListActivity.class));
                        MyApplication.getInstance().closeActivity(new ClockTypeActivity());
                        finish();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class CheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        private int i;

        public CheckedChangeListener(int i) {
            this.i = i;
        }

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            switch (i) {
                case 1:
                    if (b) {
                        weekCode.add("2");
                        weekName.add("周一");
                    } else {
                        weekCode.remove("2");
                        weekName.remove("周一");
                    }
                    break;
                case 2:
                    if (b) {
                        weekCode.add("3");
                        weekName.add("周二");
                    } else {
                        weekCode.remove("3");
                        weekName.remove("周二");
                    }
                    break;
                case 3:
                    if (b) {
                        weekCode.add("4");
                        weekName.add("周三");
                    } else {
                        weekCode.remove("4");
                        weekName.remove("周三");
                    }
                    break;
                case 4:
                    if (b) {
                        weekCode.add("5");
                        weekName.add("周四");
                    } else {
                        weekCode.remove("5");
                        weekName.remove("周四");
                    }
                    break;
                case 5:
                    if (b) {
                        weekCode.add("6");
                        weekName.add("周五");
                    } else {
                        weekCode.remove("6");
                        weekName.remove("周五");
                    }
                    break;
                case 6:
                    if (b) {
                        weekCode.add("7");
                        weekName.add("周六");
                    } else {
                        weekCode.remove("7");
                        weekName.remove("周六");
                    }
                    break;
                case 7:
                    if (b) {
                        weekCode.add("8");
                        weekName.add("周七");
                    } else {
                        weekCode.remove("8");
                        weekName.remove("周七");
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (serviceConnectionList != null && serviceConnectionList.size() > 0) {
            for (ServiceConnection serviceConnection : serviceConnectionList) {
                unbindService(serviceConnection);
            }
        }
        super.onDestroy();
    }
}
